<template>
    <div class="addEmployee">
        <div class="topNav">
            <el-divider class="topLine"><i class="lineIcon el-icon-document-copy"></i><span
                    class="lineTitle" id="optionEmployee">新建员工管理表</span></el-divider>
        </div>
        <div class="employeeSetNav">
        </div>
        <div class="addContent">
            <!--开启表单验证：:rules="rules" ref="moudle" 表单右侧验证符号 status-icon -->
            <el-form :model="employee" status-icon :rules="rules" label-width="100px" ref="employee"
                     :label-position="labelPosition">

                <el-form-item label="姓名" prop="name">
                    <el-input id="name" class="inputLine" v-model="employee.name"></el-input>
                </el-form-item>

                <el-form-item label="昵称" prop="nickName">
                    <el-input id="nickName" class="inputLine" v-model="employee.nickName"></el-input>
                </el-form-item>
                <!--绑定disabled：存在uniId则=true-->
                <el-form-item label="登录名" prop="loginName">
                    <el-input id="loginName" class="inputLine" v-model="employee.loginName"
                              :disabled="canInput"></el-input>
                </el-form-item>
                <!--不可与其他参数混合更新。否则会二次加密，这里，如果id存在，则不显示，另加修改密码功能-->
                <el-form-item label="密码" prop="password" v-show="!employee.uniId">
                    <el-input id="password" class="inputLine" v-model="employee.password"></el-input>
                </el-form-item>

                <el-form-item label="所属部门" prop="depId">
                    <el-select id="videoType" class="inputLine" v-model="employee.depId" placeholder="请选择">
                        <el-option
                                v-for="item in DEPARTMENT_NAME"
                                :key="item.key"
                                :label="item.value"
                                :value="item.key"
                                :disabled="item.disabled">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="职位" prop="position">
                    <el-input id="position" class="inputLine" v-model="employee.position"></el-input>
                </el-form-item>

                <el-form-item class="upload-icon-area" label="头像" prop="icon">
                    <big-file :upload-tile="'上传头像'" :input-id="'upload-icon'" :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="employee.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_IUSE.key"
                              :after-upload="afterUpload"></big-file>
                    <el-row class="upload-icon">
                        <el-col :span="2">
                            <div v-if="employee.icon" class="upload-icon-box">
                                <img :src="employee.icon" class="img-responsive"/>
                            </div>

                        </el-col>
                    </el-row>
                </el-form-item>

                <el-form-item label="座右铭" prop="motto">
                    <el-input type="textarea" id="motto" class="inputLine" v-model="employee.motto"></el-input>
                </el-form-item>

                <el-form-item label="简介" prop="intro">
                    <el-input type="textarea" id="intro" class="inputLine" v-model="employee.intro"></el-input>
                </el-form-item>

                <!--<el-form-item label="关联文件ID" prop="fileId">
                    <el-input id="fileId" class="inputLine" v-model="employee.fileId"></el-input>
                </el-form-item>-->

                <el-form-item label="手机号码" prop="mobile">
                    <el-input id="mobile" class="inputLine" v-model="employee.mobile"></el-input>
                </el-form-item>

                <el-form-item label="微信号码" prop="fileId">
                    <el-input id="qrCode" class="inputLine" v-model="employee.qrCode"></el-input>
                </el-form-item>

                <el-form-item label="微信二维码" prop="qrImg">
                    <big-file :upload-tile="'上传二维码'" :input-id="'upload-qrImg'" class="uploadQrImg"
                              :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="employee.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_IUSE.key"
                              :after-upload="afterQrImgUpload"></big-file>
                    <el-row class="upload-icon" >
                        <span class="logoDesc">建议尺寸：300*300px</span>
                        <el-col :span="2" v-show="employee.qrImg" >
                            <div class="upload-icon-box">
                                <img class="img-responsive" :src="employee.qrImg"/>
                            </div>
                        </el-col>
                    </el-row>

                </el-form-item>

                <el-form-item label="显示1 " prop="isShow">
                    <el-switch id="isShow" class="inputLine"
                               v-model="employee.isShow"
                               active-color="#13ce66"
                               inactive-color="#ff4949"
                               :active-value="1"
                               :inactive-value="0"
                    >
                    </el-switch>
                </el-form-item>
                <el-form-item label="工作时间" prop="fileId">
                    <div class="workTimeTemplate">
                        <el-time-select class="timePicker"
                                placeholder="起始时间"
                                v-model="workTime.startTime"
                                :picker-options="{start: '08:30',step: '00:15',end: '18:30'}">
                        </el-time-select>
                        <el-time-select
                                placeholder="结束时间"
                                v-model="workTime.endTime"
                                :picker-options="{start: '08:30',step: '00:15',end: '18:30',minTime: workTime.startTime}">
                        </el-time-select>
                    </div>
                </el-form-item>

                <el-form-item>
                    <!--这里save(formName)方法保存，ref别名的employee-->
                    <el-button id="submitBtn" type="primary" @click="save('employee')">立即创建</el-button>
                    <el-button @click="resetForm('employee')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    //import FileIcon from "../../../components/FileIcon";
    import BigFile from "../../../components/BigFile";

    export default {
        name: "AddEmployee",
        components: {BigFile},
        props: {
            list: {
                type: Function,
                default: null
            },
        },
        data() {
            let titleValidate = (rule, value, callback) => {
                //regular正则：数字、任意大小写字母，不可以有下划线
                //中文字符：[\u4e00-\u9fa5]
                //任意字母数字：[a-zA-Z0-9]
                //以...开头：^
                //以...结尾：$
                //中文字符：\u4e00-\u9fa5
                //字符限制3位以外正确：{0,3}$
                //js包含 rmValue.indexOf("!")
                let regBlank = /^[a-zA-Z0-9\s]{0,3}$/;
                let removeReg = /^\s*|\s{0,}$/g;

                let rmValue = value;

                if (value === '') {
                    callback(new Error('name不能为空'));
                } else if (regBlank.test(rmValue)) {
                    callback(new Error('必须由中文、字母、数字组成，可以有空格'));
                    let employeePath = document.getElementById("path");
                    this.employee.path = '';
                    regBlank.test(rmValue);
                } else {
                    var strApp = rmValue.replace(removeReg, "");
                    var blankApp = strApp.replace(/\s{1,}/g, "-");
                    let employeePath = document.getElementById("path");
                    employeePath.value = blankApp;
                    //需要在显示后，继续定义employeePath
                    this.employee.path = blankApp;
                    callback();
                    regBlank.test(rmValue);
                }
            };
            let nameValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("姓名不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("姓名长度至少3位"));
                } else {
                    callback();
                }
            }
            let nickNameValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("昵称不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("昵称长度至少3位"));
                } else {
                    callback();
                }
            }
            let loginNameValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("登录名不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("登录名长度至少3位"));
                } else {
                    callback();
                }
            }
            let passwordValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("密码不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("密码长度至少3位"));
                } else {
                    callback();
                }
            }
            let positionValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("职位不能为空"));
                } else if (getLength(value) < 1) {
                    callback(new Error("请选择部门"));
                } else {
                    callback();
                }
            }
            let iconValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("头像不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("头像长度至少3位"));
                } else {
                    callback();
                }
            }
            let mottoValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("座右铭不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("座右铭长度至少3位"));
                } else {
                    callback();
                }
            }
            let introValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("简介不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("简介长度至少3位"));
                } else {
                    callback();
                }
            }

            return {
                message: '这里是更新员工管理表页面',
                employee: {
                    uniId: '',
                    name: '',
                    nickName: '',
                    loginName: '',
                    password: '',
                    depId: '',
                    position: '',
                    icon: '',
                    motto: '',
                    intro: '',
                    fileId: '',
                    createTime: '',
                    updateTime: '',
                },
                labelPosition: 'left',
                canInput: false,
                rules: {
                    name: [
                        {validator: nameValidate, trigger: 'blur'}
                    ],
                    nickName: [
                        {validator: nickNameValidate, trigger: 'blur'}
                    ],
                    loginName: [
                        {validator: loginNameValidate, trigger: 'blur'}
                    ],
                    password: [
                        {validator: passwordValidate, trigger: 'blur'}
                    ],
                    position: [
                        {validator: positionValidate, trigger: 'blur'}
                    ],
                    icon: [
                        {validator: iconValidate, trigger: 'blur'}
                    ],

                },
                //文件上传：封面上传，这里的地址，vue默认搜索public，不需要添加public：../../imgs/BG-WALL.png
                imageUrl: '',
                dynamicTags: ['标签一', '标签二', '标签三'],
                inputVisible: false,
                inputValue: '',
                options: VIDEO_TYPE,
                charge: VIDEO_CHARGE,
                isShow: YES_OR_NO,
                level: LEVEL,
                status: STATUS,
                moduleTypes: MODULE_TYPE,
                SOURCE_USE_TYPE: SOURCE_USE_TYPE,
                DEPARTMENT_NAME: DEPARTMENT_NAME,
                //级联选择
                value: [],
                //工作时间
                workTime:{startTime:'',endTime:''},
            }
        },
        mounted() {
            if (this.$route.params.employee != null) {
                this.employee = this.$route.params.employee;
                this.workTime=this.employee.workTimeDto;
                let optionEmployee = document.getElementById("optionEmployee");
                let submitBtn = document.getElementById("submitBtn");
                this.canInput = true;
                optionEmployee.innerHTML = '更新员工管理表';
                submitBtn.innerHTML = "立即更新";
            }
        },
        methods: {

            //1.新增员工管理表
            save(formName) {
                let responseMsg = '';
                //md5密文，key为盐值。确保安全，后端save再进行二次加密digest
                this.employee.password = hex_md5(this.employee.password + KEY);
                //前端校验
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.employee.workTimeDto=this.workTime;
                        this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/employee/save', this.employee)
                            .then((response) => {
                                let resp = response.data;
                                responseMsg = resp.responseMsg;
                                if (resp.success) {
                                    this.$router.push("/system/manager/employee");
                                    //引入全局变量toast提示
                                    toast.success("保存成功", "bottom-end");
                                } else {
                                    this.$notify({
                                        title: '填写内容错误',
                                        message: responseMsg,
                                        position: "top-right",
                                        type: 'warning',
                                        offset:300
                                    });
                                }
                            })
                    } else {
                        this.$notify({
                            title: '填写内容错误',
                            message: '请按照提示内容填写正确信息',
                            position: "top-right",
                            type: 'warning',
                            offset:300
                        });
                        return false;
                    }
                });

            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //SEO标签
            handleClose(tag) {
                this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    this.dynamicTags.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            //级联选择器
            handleChange(value) {
                console.log(value);
            },
            //文件上传
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //接收文件上传组件传入的resp
            afterUpload(resp) {
                if (resp.success) {
                    this.employee.icon = resp.responseData.path;
                }
            },
            afterQrImgUpload(resp) {
                this.employee.qrImg = resp.responseData.path;
            }

        },
    }
</script>

<style scoped>
    /*顶部line样式*/
    .topNav {

    }

    /deep/ .el-divider__text {
        background-color: #1d7dd6;
        padding: 8px 20px;
    }

    .topLine {
        background-color: #1d7dd6;
    }

    .lineIcon {
        font-size: 22px;
        color: #ffffff;
        position: relative;
        margin-right: 5px;
    }

    .lineTitle {
        position: relative;
        font-size: 16px;
        color: #ffffff;
    }

    /*员工管理表设置导航*/
    .employeeSetNav {
        max-width: 400px;
        margin: 5px auto;

    }

    .employeeSetNavTile {
        cursor: pointer;
    }

    /*内容区位置*/
    .addContent {
        margin-left: 5%;
        margin-top: 35px;
        margin-right: 5%;
    }

    /deep/ .el-form-item {
        margin-bottom: 5px;
    }

    /*输入行控制*/
    .inputLine {
        max-width: 350px;
        float: left;
    }

    /*关键字标签*/
    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }

    .titleLeft {
        float: left;
    }

    /*SEO描述*/
    .textAreaWidth {
        max-width: 400px;
        float: left;
    }

    /*图片上传：取消upload打开的input默认按钮*/
    /deep/ input[type=file] {
        display: block;
    }

    /*错误提示*/
    #employeeTitle {
        float: left;
    }

    /deep/ .el-form-item__error {
        float: left;
        position: relative;
        line-height: 30px;
        margin-left: 10px;
    }

    /*提示框的字符颜色*/
    /deep/ .el-input__prefix, .el-input__suffix {
        color: #44cd3f;
        font-size: 18px;
    }

    /deep/ .el-input__icon {
        color: #44cd3f;
        font-size: 18px;
    }

    /*是否显示*/
    /deep/ .el-switch {
        line-height: 40px;
    }

    /*头像上传：如果没有可删除，picList*/
    .avatar-uploader {
        float: left;
    }

    .avatar-uploader {
        border: 1px dashed #a8a2a2;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;
        text-align: center;
    }

    .avatar-uploader:hover {
        border-color: #409EFF;
    }

    .avatar-uploader:hover .avatar-uploader-icon {
        color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    input[type=file] {
        display: block;
    }

    .upload-icon {
        margin-top: -50px;
        margin-bottom: 10px;
        position: relative;
    }
    .upload-icon .upload-icon-box{
        border: 1px solid #cccccc;
        padding: 5px;
        border-radius: 5px;
        overflow: hidden;
    }
    .upload-icon img{
        transition: 1s;
    }
    .upload-icon img:hover{
        transform: scale(1.5);
    }
    .upload-icon img:hover .upload-icon-box{
        border: 1px solid #1d7dd6;
    }
    /*微信二维码*/
    .uploadQrImg{
        display: block;
    }
    .logoDesc {
        position: absolute;
        display: block;
        color: #1b6d85;
        float: left;
        top: -40px;
        left: 100px;
    }
    /*工作时间*/
    .workTimeTemplate{
        float: left;
        margin-bottom: 20px;
    }
    .workTimeTemplate .timePicker{
        margin-right: 10px;
    }
</style>